package net.lab1024.sa.base.module.support.job.sample;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.base.kafka.KafkaProducerService;
import net.lab1024.sa.base.module.support.config.ConfigDao;
import net.lab1024.sa.base.module.support.config.domain.ConfigEntity;
import net.lab1024.sa.base.module.support.job.core.SmartJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 定时任务 - ES测试数据生成
 */
@Slf4j
@Service
public class SmartJobSample3 implements SmartJob {

    @Autowired
    private ConfigDao configDao;
    @Autowired
    private KafkaProducerService kafkaProducerService;
    @Autowired
    private ElasticsearchOperations elasticsearchOperations;

    // 事件类型
    private static final String[] EVENT_TYPES = {
        "login", "file_access", "firewall_alert", "ids_alert", "virus_alert",
        "system_alert", "network_alert", "database_alert"
    };

    // 事件名称
    private static final String[] EVENT_NAMES = {
        "用户登录", "文件访问", "防火墙告警", "入侵检测", "病毒告警",
        "系统告警", "网络告警", "数据库告警"
    };

    // 危险等级
    private static final String[] SEVERITY_LEVELS = {
        "1", "2", "3", "4", "5"
    };

    // 日志来源
    private static final Integer[] LOG_SOURCES = {
        1, 2, 3  // 1-火绒，2-waf，3-edr
    };

    // 攻击结果
    private static final String[] ATTACK_RESULTS = {
        "成功", "失败", "未知"
    };

    // 资产类型
    private static final String[] ASSET_TYPES = {
        "0", "1"  // 0-非内部资产，1-内部资产
    };

    /**
     * 生成ES测试数据
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public String run(String param) {
        JSONObject jsonObject = JSONObject.parseObject(param);
        int count = 100;
        List<Map<String, Object>> events = new ArrayList<>();
        Random random = new Random();

        for (int i = 0; i < count; i++) {
            Map<String, Object> event = new HashMap<>();
            
            // 生成随机时间（最近7天内）
            LocalDateTime eventTime = LocalDateTime.now().minusSeconds(random.nextInt(7 * 24 * 60 * 60));
            String formattedTime = eventTime.format(DateTimeFormatter.ISO_DATE_TIME);
            long timestamp = new Date().getTime();

            // 基础元数据
            event.put("event_id", "EVENT-" + generateRandomString(32));
            event.put("es_id", UUID.randomUUID().toString());
            event.put("@timestamp", timestamp);
            
            int eventTypeIndex = random.nextInt(EVENT_TYPES.length);
            event.put("event_type", EVENT_TYPES[eventTypeIndex]);
//            event.put("event_name", EVENT_NAMES[eventTypeIndex]);
//            event.put("event_name", "测试告警");
            event.put("event_rule", "RULE-" + generateRandomString(8));
            event.put("event_time", formattedTime);
            event.put("recive_time", formattedTime);
            event.put("severity", SEVERITY_LEVELS[random.nextInt(SEVERITY_LEVELS.length)]);
            event.put("name", LOG_SOURCES[random.nextInt(LOG_SOURCES.length)]);

            // 设备信息
            if(null!=jsonObject.get("deviceName")){
                event.put("device_name", jsonObject.get("deviceName"));
            }else{
                event.put("device_name", "DEVICE-" + generateRandomString(8));
            }

            event.put("device_ip", generateRandomIp());
            event.put("attack_packets", generateRandomString(50));

            // 资产信息
            event.put("dst_cmdb_name", "ASSET-" + generateRandomString(8));
            event.put("src_cmdb_name", "ASSET-" + generateRandomString(8));
            event.put("src_security_domains", "域-" + generateRandomString(4));
            event.put("dst_security_domains", "域-" + generateRandomString(4));

            // 源端点信息
            event.put("src_ip", generateRandomIp());
            event.put("src_type", ASSET_TYPES[random.nextInt(ASSET_TYPES.length)]);
            event.put("src_port", String.valueOf(random.nextInt(65535)));
            event.put("src_hostname", "HOST-" + generateRandomString(8));
            event.put("src_mac", generateRandomMac());
            event.put("src_leder", "负责人-" + generateRandomString(4));

            // 目标端点信息
            event.put("dst_ip", generateRandomIp());
            event.put("dst_leder", "负责人-" + generateRandomString(4));
            event.put("dst_type", ASSET_TYPES[random.nextInt(ASSET_TYPES.length)]);
            event.put("dst_port", random.nextInt(65535));
            event.put("dst_hostname", "HOST-" + generateRandomString(8));

            // 用户信息
            event.put("user_name", "user" + generateRandomString(4));

            // 网络协议信息
            event.put("req_method", "GET,POST,PUT,DELETE".split(",")[random.nextInt(4)]);
            event.put("req_url", "http://example.com/" + generateRandomString(8));
            event.put("req_referer", "http://referer.com/" + generateRandomString(8));
            event.put("req_status", random.nextInt(600));
            event.put("req_user_agent", "Mozilla/5.0 " + generateRandomString(20));
            event.put("req_host", "host" + generateRandomString(8) + ".com");
            event.put("req_header", "{header: value}");
            event.put("reqxff", generateRandomIp());
            event.put("req_cookie", "cookie" + generateRandomString(8));
            event.put("req_xwafuuid", generateRandomString(32));

            // 威胁情报
            event.put("threat_category", "威胁-" + generateRandomString(8));
            event.put("threat_signature", "特征-" + generateRandomString(8));
            Map<String, Object> threatIndicators = new HashMap<>();
            threatIndicators.put("type", "恶意IP");
            threatIndicators.put("confidence", random.nextInt(100));
            threatIndicators.put("severity", SEVERITY_LEVELS[random.nextInt(SEVERITY_LEVELS.length)]);
            threatIndicators.put("last_seen", formattedTime);
            event.put("threat_indicators", threatIndicators);

            // 地理位置
            event.put("geo_country", "中国");
            event.put("srcgeolat", String.valueOf(30 + random.nextDouble()));
            event.put("srcgeolon", String.valueOf(120 + random.nextDouble()));
            event.put("srcgeocity", "杭州");
            event.put("dstgeocountry", "中国");
            event.put("dstgeolat", String.valueOf(30 + random.nextDouble()));
            event.put("dstgeolon", String.valueOf(120 + random.nextDouble()));
            event.put("dstgeocity", "杭州");

            // 事件相关
            event.put("protocol", "TCP,UDP,HTTP,HTTPS".split(",")[random.nextInt(4)]);
            event.put("raw_log", "原始日志-" + generateRandomString(50));
            event.put("blocked", random.nextBoolean() ? "1" : "0");
            event.put("action", "处置-" + generateRandomString(8));
            event.put("deviceos", "Windows,Linux,Unix".split(",")[random.nextInt(3)]);
            event.put("c_type", "连接方式-" + generateRandomString(4));

            // WAF相关
            event.put("query_string", "query=" + generateRandomString(10));
            event.put("payload", "payload-" + generateRandomString(20));
            event.put("resp_header", "{resp: header}");
            event.put("req_end_time", formattedTime);
            event.put("req_start_time", formattedTime);

            // EDR/火绒相关
            event.put("white_rule_effect", random.nextBoolean() ? "1" : "0");
            event.put("recname", "记录-" + generateRandomString(8));
            event.put("taskname", "任务-" + generateRandomString(8));
//            event.put("md5", generateRandomString(32));
            event.put("procname", "进程-" + generateRandomString(8));
            event.put("cmdline", "cmd " + generateRandomString(16));
            event.put("p_cmdline", "parent " + generateRandomString(16));
            event.put("path_name", "/path/" + generateRandomString(8));
            event.put("os_type", "Windows,Linux".split(",")[random.nextInt(2)]);
            event.put("res_data", "数据-" + generateRandomString(16));
            event.put("res_path", "/res/" + generateRandomString(8));
            event.put("recnameVal", "软件-" + generateRandomString(8));
            event.put("mail_from", "from@example.com");
            event.put("mail_to", "to@example.com");
            event.put("detail", "详情-" + generateRandomString(20));
            event.put("func", "功能-" + generateRandomString(8));
            event.put("kbid", "KB-" + generateRandomString(8));
            event.put("level", "级别-" + generateRandomString(4));
            event.put("file_operation", "操作-" + generateRandomString(8));

            // 组织和资产信息
            event.put("srcorganization", "组织-" + generateRandomString(8));
            event.put("srcassetName", "资产-" + generateRandomString(8));
            event.put("dstorganization", "组织-" + generateRandomString(8));
            event.put("dstassetName", "资产-" + generateRandomString(8));
            event.put("host_state", ATTACK_RESULTS[random.nextInt(ATTACK_RESULTS.length)]);
            event.put("confidence", String.valueOf(random.nextInt(100)));
            event.put("file_name", "file-" + generateRandomString(8) + ".txt");
            event.put("file_type", "text/plain");
            event.put("subject", "主题-" + generateRandomString(16));
            event.put("file_size", String.valueOf(random.nextInt(10000)));
            event.put("name_honeypot", "蜜罐-" + generateRandomString(8));
            event.put("attack_result", ATTACK_RESULTS[random.nextInt(ATTACK_RESULTS.length)]);
            event.put("attack_type", "攻击-" + generateRandomString(8));
            event.put("super_type", "阶段-" + generateRandomString(8));
            event.put("detail_info", "信息-" + generateRandomString(20));
            event.put("packet_data", "数据包-" + generateRandomString(20));
            event.put("username", "user" + generateRandomString(8));
            event.put("login_count", String.valueOf(random.nextInt(100)));
            event.put("passwd", "pass" + generateRandomString(8));
            event.put("rsp_count", String.valueOf(random.nextInt(1000)));
            event.put("rsp_start_time", formattedTime);
            event.put("rsp_end_time", formattedTime);
            event.put("rsp_location", "位置-" + generateRandomString(8));
            event.put("rsp_code", String.valueOf(random.nextInt(600)));
            event.put("rsp_body", "响应体-" + generateRandomString(20));
            event.put("proxy_address", generateRandomIp());
            event.put("proxy_type", "代理-" + generateRandomString(4));
            event.put("tool_type", "工具-" + generateRandomString(8));
            event.put("sql_stat", "SELECT * FROM " + generateRandomString(8));
            event.put("agent_name", "代理-" + generateRandomString(8));
            event.put("rule_alert_name", "规则-" + generateRandomString(8));
            event.put("rule_batch", "批次-" + generateRandomString(8));
            event.put("rule_alert_level", String.valueOf(random.nextInt(5) + 1));
            event.put("rule_alert_links", "链-" + generateRandomString(8));
            event.put("rule_alert_result", "结果-" + generateRandomString(8));
            event.put("rule_alert_reson", "原因-" + generateRandomString(16));
            event.put("rule_alert_disposal", "建议-" + generateRandomString(16));
//            event.put("rule_code", "CODE-" + generateRandomString(8));

            events.add(event);
        }

        // 批量写入ES
        String indexName = "event-base-" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        for (Map<String, Object> event : events) {
            elasticsearchOperations.save(event, IndexCoordinates.of(indexName));
//            kafkaProducerService.sendMessage("topic-evnet-base", JSONObject.toJSONString(event));
        }

        log.info("Successfully generated and inserted {} test events into ES index: {}", count, indexName);
        return String.format("成功生成并写入 %d 条测试数据到ES索引: %s", count, indexName);
    }

    // 生成随机IP地址
    private String generateRandomIp() {
        Random r = new Random();
        return r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256);
    }

    // 生成随机MAC地址
    private String generateRandomMac() {
        Random r = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            if (i > 0) sb.append(":");
            int value = r.nextInt(256);
            sb.append(String.format("%02X", value));
        }
        return sb.toString();
    }

    // 生成随机字符串
    private String generateRandomString(int length) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            sb.append(chars.charAt(random.nextInt(chars.length())));
        }
        return sb.toString();
    }
}
